package com.crime.crimemonitorclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import org.apache.http.HttpStatus;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.location.Location;
import android.util.Log;
import android.widget.Toast;

import com.crimemonitor.library.CrimesSummary;
import com.google.gson.Gson;

public class GetCrimeSummaryAsyncTask extends RetainedAsyncTask<CrimesSummary>
{
	private Exception						mException;
	private final URL						mServiceURL;
	private final long						mStartDate;
	private final long						mEndDate;
	private final Location					mLocation;
	
	public GetCrimeSummaryAsyncTask(URL serviceURL, long startDate,
			long endDate, Location location,
			AsyncTaskHandler<CrimesSummary> asyncTaskHandler)
			throws NullPointerException, IllegalArgumentException
	{
		super(asyncTaskHandler);

		if (location == null)
			throw new NullPointerException("location");

		if (serviceURL == null)
			throw new NullPointerException("serviceURL");

		if (startDate > endDate)
			throw new IllegalArgumentException(
					"endDate must be greater or equal than startDate");

		this.mServiceURL = serviceURL;
		this.mStartDate = startDate;
		this.mEndDate = endDate;
		this.mLocation = location;
	}

	private void stall(long time)
	{
		try
		{
			Thread.sleep(time);
		}
		catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			Log.d("stalling",
					"Error while trying to stall GetCrimeSummaryAsyncTask.", e);
		}
	}

	@Override
	protected CrimesSummary doInBackground(Void... args)
	{
		HttpURLConnection conn = null;
		BufferedReader isReader = null;

		// this.stall(20 * 1000);

		try
		{
			URL serviceURL = new URL(String.format(Locale.ENGLISH,
					"%s/summary?startDate=%d&endDate=%d&lat=%f&lon=%f",
					this.mServiceURL.toString(), this.mStartDate,
					this.mEndDate, this.mLocation.getLatitude(),
					this.mLocation.getLongitude()));

			conn = (HttpURLConnection) serviceURL.openConnection();
			isReader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));

			if (conn.getResponseCode() == HttpStatus.SC_OK)
			{
				StringBuilder sb = new StringBuilder();
				String readLine;
				while (!this.isCancelled()
						&& (readLine = isReader.readLine()) != null)
				{
					sb.append(readLine);
					sb.append("\n");
				}

				if (this.isCancelled())
					return null;

				CrimesSummary summary = new Gson().fromJson(sb.toString(),
						CrimesSummary.class);

				return summary;

			}
			else
			{
				this.mException = new IOException(conn.getResponseMessage());
			}
		}
		catch (Exception e)
		{
			// pri jakekoli vyjimce ji zaznamenej
			this.mException = e;
			// TODO: a task zrus???
			this.cancel(false);
		}
		finally
		{
			try
			{
				if (conn != null)
					conn.disconnect();

				if (isReader != null)
				{
					isReader.close();

				}
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		return null;
	}

	Exception getException()
	{
		return this.mException;
	}

	/**
	 * @return the location
	 */
	public Location getLocation()
	{
		return mLocation;
	}
}
